package com.magima.core.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;

public class PrefRepository extends Repository{
	protected SharedPreferences mPref;
	public PrefRepository(StringProcessor processor, Context context, String repository) {
		super(processor);
		mName = repository;
		mPref = context.getSharedPreferences(repository, Context.MODE_MULTI_PROCESS);
	}
	public PrefRepository(Context context, String repository) {
		this(null, context, repository);
	}
	
	@Override
	public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
		mPref.registerOnSharedPreferenceChangeListener(listener);
	}
	
	@Override
	public void saveString(String key, String data) {
		mPref.edit().putString(key, mProcessor.encodeString(data) ).commit();
	}
	
	@Override
	public String loadString(String key) {
		String code = mPref.getString(key, null);
		if ( code == null )
			return null;
		return mProcessor.decodeString( code);
	}
	
	@Override
	public void remove(String key){
		mPref.edit().remove(key).commit();
	}
	
	@Override
	public void remove() {
		mPref.edit().clear().commit();
	}
	
	@Override
	public List<String> loadAllString() {
		List<String> list = new ArrayList<String>();
		Map<String, ?> map = mPref.getAll();
		Set<String> set = map.keySet();
		for ( String key : set ){
			String code = (String) map.get(key); 
			if ( code != null )
				list.add( mProcessor.decodeString( code) );
		}
		return list;
	}
}
